package com.gome.ocean.controller.authority;

import java.rmi.RemoteException;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.gome.framework.AppContext;
import com.gome.framework.Env;
import com.gome.ocean.common.constants.Constants;
import com.gome.ocean.common.constants.RoleContants;
import com.gome.ocean.common.enums.SmsValid;
import com.gome.ocean.common.exception.UserServiceException;
import com.gome.ocean.common.utils.RandomUtil;
import com.gome.ocean.common.utils.ResponsePage;
import com.gome.ocean.dao.model.authority.ProjectBO;
import com.gome.ocean.dao.model.authority.SmsBO;
import com.gome.ocean.dao.model.authority.User;
import com.gome.ocean.dao.model.authority.UserLoginLogoutBO;
import com.gome.ocean.service.authority.IUserLoginLogoutService;
import com.gome.ocean.service.authority.ProjectService;
import com.gome.ocean.service.authority.SmsService;
import com.gome.ocean.service.authority.UserService;
import com.gome.ocean.service.base.AuthorityBaseController;

/**
 * @author zhangguoqing 2016年11月1日 下午4:09:34
 * @since 5.0.0
 */
@Controller
@RequestMapping("/register")
public class RegisterController extends AuthorityBaseController {

    private static final Logger LOG = LoggerFactory.getLogger(RegisterController.class);

    @Autowired
    private ProjectService          projectService;
    @Autowired
    private UserService             userService;
    @Autowired
    private SmsService              smsService;
    @Autowired
    private IUserLoginLogoutService userLoginLogoutService;

    @RequestMapping("/getResPage")
    public ModelAndView getRegisterUser(HttpServletRequest request, ModelAndView mav) {
        List<ProjectBO> projectLists = projectService.getAllProjects();
        mav.addObject("projectLists", projectLists);
        mav.setViewName("authority/register/register-user");
        return mav;
    }

    @RequestMapping("/sendRegisterSms")
    @ResponseBody
    public ResponsePage sendRegisterSms(HttpServletRequest request) {
        ResponsePage page = new ResponsePage();
        Env env = AppContext.getEnv();
        String envirVal = env.get("environValue");
        try {
            String email = request.getParameter("email");
            String telphone = request.getParameter("telphone");
            User user = userService.findUser(email);
            if (user != null) {
                return page.setErrorMsg("该用户(" + email + ")已经存在,不要重复注册!");
            }
            if (StringUtils.isBlank(telphone)) {
                return page.setErrorMsg("该用户手机号为空,请输入手机号!");
            }
            SmsBO smsBO = new SmsBO();
            smsBO.setPhone(telphone);
            smsBO.setIsValid(SmsValid.VALID.getValue());
            smsBO = smsService.findSmsBOByPhone(smsBO);
            if (smsBO != null) {
                smsService.sendSms(envirVal, telphone, smsBO.getCode(), Constants.businessName, Constants.temp_id);
                return page.setSuccessMsg("短信发送成功");
            } else {
                smsBO = new SmsBO();
                smsBO.setPhone(telphone);
                smsBO.setIsValid(SmsValid.VALID.getValue());
                smsBO.setCode(RandomUtil.generateUpperString(4));
                smsService.saveSmsBO(smsBO);
                smsService.sendSms(envirVal, telphone, smsBO.getCode(), Constants.businessName, Constants.temp_id);
                return page.setSuccessMsg("短信发送成功");
            }
        } catch (Exception e) {
            return page.setErrorMsg("发送短信过程中发生异常，异常信息为：" + e.getMessage());
        }
    }

    @RequestMapping("/newRegisterUser")
    @ResponseBody
    public ResponsePage newRegisterUser(HttpServletRequest request) throws RemoteException {
        String email = request.getParameter("email");
        String password = request.getParameter("password");
        String telphone = request.getParameter("telphone");
        String messageValid = request.getParameter("messageValid");
        String project = request.getParameter("project");
        ResponsePage page = new ResponsePage();
        if (StringUtils.isBlank(email)) {
            return page.setErrorMsg("email不能为空");
        }
        if (!email.matches(Constants.REG_EMAIL)) {
            return page.setErrorMsg("email格式不正确，正确格式为：XXX@gomeplus.com");
        }
        if (StringUtils.isBlank(password)) {
            return page.setErrorMsg("密码不能为空");
        }
        if (StringUtils.isBlank(project)) {
            return page.setErrorMsg("项目组不能为空");
        }
        User user;
        try {
            user = userService.findUser(email);
        } catch (UserServiceException e) {
            LOG.error(e.getMessage(), e);
            return page.setErrorMsg(e.toString());
        }
        if (null != user) {
            return page.setErrorMsg("该用户(" + email + ")已经存在,不能重复注册!");
        }
        // 用户注册日志信息
        try {
            Map<String, Object> map = super.getLocalHostIpAndNameAndSysInfo();
            UserLoginLogoutBO logoutBO = new UserLoginLogoutBO();
            logoutBO.setEmail(email);
            logoutBO.setLoginTime(new Date());
            logoutBO.setSrcIp(map.get("hostIp").toString());
            logoutBO.setServerIp(super.getIpAddr(request));
            logoutBO.setLocalHostName(map.get("hostName").toString());
            userLoginLogoutService.insertUserLoginLogoutInfo(logoutBO);
        } catch (Exception e) {
            LOG.error(e.toString());
        }
        LOG.debug("当前注册用户：" + email + "," + "登陆IP：" + super.getIpAddr(request));
        User newUser = new User();
        newUser.setEmail(email);
        newUser.setPassword(password);
        newUser.setCreateTime(new Date());
        String deptCode = this.getDepartCodeByAccount(email.split("@")[0]);
        if (StringUtils.isNotBlank(deptCode)) {
            if (deptCode.equals(RoleContants.DBAD_DEPTMENT_CODE)) {
                newUser.setRole(RoleContants.ROLE_DBA);
                newUser.setRoleId(RoleContants.ROLE_DBA_ID);
            } else {
                newUser.setRole(RoleContants.ROLE_USER);
                newUser.setRoleId(RoleContants.ROLE_USER_ID);
            }
            newUser.setTelphone(telphone);
            try {
                ProjectBO proBean = projectService.findProjectByName(project);
                if (proBean.getProjectName().equals(RoleContants.DBA_PROJECT_NAME)) {
                    if (!deptCode.equals(RoleContants.DBAD_DEPTMENT_CODE)) {
                        return page.setErrorMsg("注册失败,您当前并不属于DBA部门成员!");
                    }
                }
                StringBuilder sb = new StringBuilder();
                String[] proUsers = proBean.getProjectUser().split(",");
                for (String pro : proUsers) {
                    sb.append(pro).append(",");
                }
                sb.append(email);
                proBean.setProjectUser(sb.toString());
                boolean isValid = this.smsService.isValid(telphone, messageValid);
                if (!isValid) {
                    return page.setErrorMsg("验证码错误！");
                }
                boolean inUserFlag = userService.insertUser(newUser);
                if (inUserFlag) {
                    boolean flag = projectService.updateProject(proBean);
                    if (flag) {
                        return page.setSuccessMsg("注册用户成功,点击返回登录!");
                    } else {
                        return page.setErrorMsg("注册失败！更新项目组过程发生错误,无法加入到当前项目组中.请联系管理员!");
                    }
                } else {
                    return page.setErrorMsg("注册失败");
                }

            } catch (Exception e) {
                LOG.error(e.getMessage(), e);
                return page.setErrorMsg("注册用户过程中发生异常，异常信息为：" + e.getMessage());
            }
        }
        return page.setErrorMsg("注册用户失败，当前用户在OA中不存在");
    }

}
